﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Admin.NET.Application;

/// <summary>
/// 库位表服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class warehouseLocationService : IDynamicApiController, ITransient
{

    private readonly SqlSugarRepository<warehouselocation> _warehouseLocationRep;
    private readonly ISqlSugarClient _sqlSugarClient;
    private readonly SysDictTypeService _sysDictTypeService;

    public warehouseLocationService(SqlSugarRepository<warehouselocation> warehouseLocationRep, ISqlSugarClient sqlSugarClient, SysDictTypeService sysDictTypeService)
    {
        _warehouseLocationRep = warehouseLocationRep;
        _sqlSugarClient = sqlSugarClient;
        _sysDictTypeService = sysDictTypeService;
    }

    /// <summary>
    /// 分页查询库位表 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询库位表")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<warehouseLocationOutput>> Page(PagewarehouseLocationInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _warehouseLocationRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.warehouseLocation_code.Contains(input.Keyword) || u.warehouseLocation_name.Contains(input.Keyword) || u.description.Contains(input.Keyword) || u.warehouse_location_name.Contains(input.Keyword) || u.warehouse_state.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.warehouseLocation_code), u => u.warehouseLocation_code.Contains(input.warehouseLocation_code.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.warehouseLocation_name), u => u.warehouseLocation_name.Contains(input.warehouseLocation_name.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.description), u => u.description.Contains(input.description.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.warehouse_location_name), u => u.warehouse_location_name.Contains(input.warehouse_location_name.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.warehouse_state), u => u.warehouse_state.Contains(input.warehouse_state.Trim()))
            .WhereIF(input.shelfstorageareaid != null, u => u.shelfstorageareaid == input.shelfstorageareaid)
            .LeftJoin<shelfstoragearea>((u, shelfstoragearea) => u.shelfstorageareaid == shelfstoragearea.Id)
            .Select((u, shelfstoragearea) => new warehouseLocationOutput
            {
                Id = u.Id,
                shelfstorageareaid = u.shelfstorageareaid,
                shelfstorageareaFkDisplayName = $"{shelfstoragearea.shelfstoragearea_code}-{shelfstoragearea.shelfstoragearea_name}",
                warehouseLocation_code = u.warehouseLocation_code,
                warehouseLocation_name = u.warehouseLocation_name,
                description = u.description,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
                warehouse_location_name = u.warehouse_location_name,
                warehouse_state = u.warehouse_state,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取库位表详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取库位表详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<warehouselocation> Detail([FromQuery] QueryByIdwarehouseLocationInput input)
    {
        return await _warehouseLocationRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加库位表 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加库位表")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddwarehouseLocationInput input)
    {
        var entity = input.Adapt<warehouselocation>();
        return await _warehouseLocationRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新库位表 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新库位表")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdatewarehouseLocationInput input)
    {
        var entity = input.Adapt<warehouselocation>();
        await _warehouseLocationRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除库位表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除库位表")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeletewarehouseLocationInput input)
    {
        var entity = await _warehouseLocationRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _warehouseLocationRep.FakeDeleteAsync(entity);   //假删除
        //await _warehouseLocationRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除库位表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除库位表")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeletewarehouseLocationInput> input)
    {
        var exp = Expressionable.Create<warehouselocation>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _warehouseLocationRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _warehouseLocationRep.FakeDeleteAsync(list);   //假删除
        //return await _warehouseLocationRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDatawarehouseLocationInput input)
    {
        var shelfstorageareaidData = await _warehouseLocationRep.Context.Queryable<shelfstoragearea>()
            .InnerJoinIF<warehouselocation>(input.FromPage, (u, r) => u.Id == r.shelfstorageareaid)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.shelfstoragearea_code}-{u.shelfstoragearea_name}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "shelfstorageareaid", shelfstorageareaidData },
        };
    }
    
    /// <summary>
    /// 导出库位表记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出库位表记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PagewarehouseLocationInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportwarehouseLocationOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        var warehouse_stateDictMap = _sysDictTypeService.GetDataList(new GetDataDictTypeInput { Code = "Enumeration_of_cargo_location_status" }).Result.ToDictionary(x => x.Value, x => x.Label);
        list.ForEach(e => {
            e.warehouse_stateDictLabel = warehouse_stateDictMap.GetValueOrDefault(e.warehouse_state ?? "", e.warehouse_state);
        });
        return ExcelHelper.ExportTemplate(list, "库位表导出记录");
    }
    
    /// <summary>
    /// 下载库位表数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载库位表数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportwarehouseLocationOutput>(), "库位表导入模板", (_, info) =>
        {
            if (nameof(ExportwarehouseLocationOutput.shelfstorageareaFkDisplayName) == info.Name) return _warehouseLocationRep.Context.Queryable<shelfstoragearea>().Select(u => $"{u.shelfstoragearea_code}-{u.shelfstoragearea_name}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入库位表记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入库位表记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var warehouse_stateDictMap = _sysDictTypeService.GetDataList(new GetDataDictTypeInput { Code = "Enumeration_of_cargo_location_status" }).Result.ToDictionary(x => x.Label!, x => x.Value);
            var stream = ExcelHelper.ImportData<ImportwarehouseLocationInput, warehouselocation>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 货架
                    var shelfstorageareaidLabelList = pageItems.Where(x => x.shelfstorageareaFkDisplayName != null).Select(x => x.shelfstorageareaFkDisplayName).Distinct().ToList();
                    if (shelfstorageareaidLabelList.Any()) {
                        var shelfstorageareaidLinkMap = _warehouseLocationRep.Context.Queryable<shelfstoragearea>().Where(u => shelfstorageareaidLabelList.Contains($"{u.shelfstoragearea_code}-{u.shelfstoragearea_name}")).ToList().ToDictionary(u => $"{u.shelfstoragearea_code}-{u.shelfstoragearea_name}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.shelfstorageareaid = shelfstorageareaidLinkMap.GetValueOrDefault(e.shelfstorageareaFkDisplayName ?? "");
                            if (e.shelfstorageareaid == null) e.Error = "货架链接失败";
                        });
                    }
                    
                    // 映射字典值
                    foreach(var item in pageItems) {
                        if (string.IsNullOrWhiteSpace(item.warehouse_stateDictLabel)) continue;
                        item.warehouse_state = warehouse_stateDictMap.GetValueOrDefault(item.warehouse_stateDictLabel);
                        if (item.warehouse_state == null) item.Error = "状态字典映射失败";
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<warehouselocation>>();
                    
                    var storageable = _warehouseLocationRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.warehouseLocation_code?.Length > 50, "编码长度不能超过50个字符")
                        .SplitError(it => it.Item.warehouseLocation_name?.Length > 50, "库位名称长度不能超过50个字符")
                        .SplitError(it => it.Item.description?.Length > 100, "描述长度不能超过100个字符")
                        .SplitError(it => it.Item.warehouse_location_name?.Length > 50, "名称长度不能超过50个字符")
                        .SplitError(it => it.Item.warehouse_state?.Length > 32, "状态长度不能超过32个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
